#!/bin/bash
# anaconda-generator: generate services needed for anaconda operation

# only run in the Anaconda installation environment
ANACONDA_TARGET="/lib/systemd/system/anaconda.target"
CURRENT_DEFAULT_TARGET=$(readlink /etc/systemd/system/default.target)

if ! { [ "$ANACONDA_TARGET" = "$CURRENT_DEFAULT_TARGET" ] || grep -q 'systemd.unit=anaconda.target' /proc/cmdline ;} ; then
    exit 0
fi

# set up dirs
systemd_dir=/lib/systemd/system
target_dir="$1/anaconda.target.wants"
mkdir -p "$target_dir"

# create symlink anaconda.target.wants/SERVICE@TTY.service
service_on_tty() {
    local service="$1" tty="$2"
    local service_instance="${service/@.service/@$tty.service}"
    ln -sf "$systemd_dir/$service" "$target_dir/$service_instance"
}

# find the real tty for /dev/console
tty="console"
while [ -f "/sys/class/tty/$tty/active" ]; do
    tty=$(< "/sys/class/tty/$tty/active")
    tty=${tty##* } # last item in the list
done
consoletty="$tty"

# put anaconda's tmux session on the console
service_on_tty anaconda-tmux@.service "$consoletty"

# put a shell on the first virtualization console we find
for tty in hvc0 hvc1 xvc0 hvsi0 hvsi1 hvsi2; do
    [ "$tty" = "$consoletty" ] && continue
    if [ -d /sys/class/tty/$tty ]; then
        service_on_tty anaconda-shell@.service $tty
        break
    fi
done

ln -sf "$systemd_dir/anaconda-nm-config.service" "$target_dir/anaconda-nm-config.service"
ln -sf "$systemd_dir/anaconda-nm-disable-autocons.service" "$target_dir/anaconda-nm-disable-autocons.service"
ln -sf "$systemd_dir/anaconda-nm-disable-autocons-rhel.service" "$target_dir/anaconda-nm-disable-autocons-rhel.service"
ln -sf "$systemd_dir/anaconda-pre.service" "$target_dir/anaconda-pre.service"
ln -sf "$systemd_dir/anaconda-import-initramfs-certs.service" "$target_dir/anaconda-import-initramfs-certs.service"
